/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



Components.utils.import("resource://addon/Preferences.js");

var hNameMail="chrome://mailLogin";
var hNameAttn="chrome://omsLogin";
var hNameIb="chrome://IbLogin";
var subURL=null;
var httprealmMail="Mail Login";
var httprealmAttn="Attn Login";
var httprealmIb="Ib Login";
var attnLoginURL=getPreferenceVal("extensions.commlink.attendenceURL","");
var w="";
var logincount=0;
var loginName={

    facebook:"email",
    gmail:"Email",
    yahoo:"login",
    csebuet:"Email",
    cmail:"Email"

}



function createCookie(name,value,days) {
    var expires="";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
	
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}



function HTMLParser(aHTMLString){
    var parseDOM = content.document.createElement('div');
    parseDOM.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"]
        .getService(Components.interfaces.nsIScriptableUnescapeHTML)
        .parseFragment(aHTMLString, false, null, parseDOM));
    return parseDOM;
}
function getPreferenceVal(prefname,defaultval)
{
    return Preferences.get(prefname,defaultval);
}

function showComlinkMainPage()
{
    var URI="www.commlinkinfotech.com";
    makePostRequest(URI,"");
}
function attendanceLogin()
{
    //var loginPostaVar={username:"parvez",password:"159357258456",action:"makeLoginLogout",requestedaction:"login"};


    
    var uName=getPreferenceVal("extensions.commlink.attnid","");
    var password="";
    var uLoginMessage="You didn't logout last time. Please talk to hr first. He will fix it.";

    if(uName!="")
    {

        password=getPassword(hNameAttn,subURL,httprealmAttn,uName);
        var loginPostaVar={
            username:uName,
            password:password,
            action:"makeLoginLogout",
            requestedaction:"login"
        };
        var postUrl=getPreferenceVal("extensions.commlink.attendanceURL","");
        ajaxRequest("post",postUrl ,loginPostaVar,function serverRsp(msg)
        {
            

            
            var message=msg.match(/Messages[\w\s<\/>='#":;(,)%-]+&[a-z]+;([\w.'\s]+)/i);
            if(message!=null)
            {
                alert(message[1]);
                if(message[1]==uLoginMessage)
                {
                    window.openDialog("chrome://sample/content/UnclosedLoginTime.xul", "Last LogOutTime", "modal=yes,chrome=yes,centerscreen=yes")
                }
                else
                {
                    makePostRequest(postUrl,"");
                }
            }
            else
            {
                makePostRequest(postUrl,"");
            }
       
        },true,true);

    }
    else
    {
        alert("Set your account first");
        window.openDialog("chrome://sample/content/pref.xul", "Settings","modal=yes,chrome=yes,centerscreen=yes");
    }
   
}
function attendanceLogOut()
{
    ajaxRequest("get", "http://172.16.0.3/oms/ocp/showDocument.php?documentid=45","", ajaxresp,false,true);
}
function mailLogin()
{
   
    var URI=getPreferenceVal("extensions.commlink.mailLoginURL","");
    var mailUserId=getPreferenceVal("extensions.commlink.mailid","");
    var password="";
    var postData="";

    try
    {
        if(mailUserId!="")
        {
        
            password=getPassword(hNameMail,subURL,httprealmMail,mailUserId);
            alert(password);
            postData="login_username="+mailUserId+"&secretkey="+password+"&js_autodetect_results=1";
            makePostRequest(URI,postData);
        }
        else
        {
            alert("You didn't set your account");
            showSettings();

        }
    }catch(msg)
    {
        alert(msg);
    }

}

function viewAccountStatement()
{

   
    var w=openXulDialogue("chrome://sample/content/statement.xul", "Account Statement","modal=no,chrome=yes,centerscreen=yes").focus();
    
    
   

}

function showStatement(type)
{
    
    salaryAccountLogin(type);
    $("#idstat").attr("hidden","true");
    return false;
}
function salaryAccountLogin(type)
{
    

    try
    {
        var loginURI=getPreferenceVal("extensions.commlink.ibloginurl","");
        var uCodeIb=getPreferenceVal("extensions.commlink.ibusercode","");
        var uAccNo=getPreferenceVal("extensions.commlink.ibuseraccno");
        var bEnquiryURI=getPreferenceVal("extensions.commlink.ibbenqurl","");
        var statURI="http://ib.trustbank.com.bd/statement.asp"
        var postRequestFrom="";
        if(type==1)
        {
       
        
            var objDate=document.getElementById("fdate").dateValue ;
            var startDate=objDate.getDate()+"/"+(objDate.getMonth()+1)+"/"+objDate.getFullYear();
            objDate=document.getElementById("tdate").dateValue ;
            var endDate=objDate.getDate()+"/"+(objDate.getMonth()+1)+"/"+objDate.getFullYear();
        
        
        }
    
    
    
        var password="";

    
        if(uCodeIb!="")
        {
            password=getPassword(hNameIb,subURL,httprealmIb,uCodeIb);
            var inStr=new String(password)
            var outStr=new String();
    

            for(i=0;i<inStr.length;i++)
            {
        
                if(inStr[i]>=0 && inStr[i]<=9)
                {
                    //still confused about this problem
                    outStr=outStr+"%26%23"+(inStr.charCodeAt(i)+80)+"%3B";
                }
                else
                {
                    outStr=outStr+String.fromCharCode(inStr.charCodeAt(i)+80);
                }
            }
      
        
            var postData="Username="+uCodeIb+"&Password="+outStr;
            var postLoginFunc="";

            if(type==0)
            {
                postRequestFrom="chrome";
                postLoginFunc=tabListener(type,bEnquiryURI,{
                    accNo:uAccNo
                },postRequestFrom)
                
            }
            else if(type==1)
            {
                try{
            
                    postRequestFrom="window";
                    postLoginFunc=tabListener(type,statURI,{
                        accNo:uAccNo,
                        fDate:startDate,
                        tDate:endDate
                    },postRequestFrom)
           
                }catch(msg)
                {
                    alert(msg);
                }
            }
        
            var newTabBrowser=makePostRequest(loginURI,postData,postRequestFrom);
            newTabBrowser.addEventListener("load",postLoginFunc,true);

        
        
    
        }
        else
        {
            alert("You didn't set your account");
            showSettings();

        }
    }catch(msg)
    {
        alert(msg);
    }

}
function salaryAccoutLogoff()
{
    var URI=getPreferenceVal("extensions.commlink.iblogoffurl","");
    sendGetRequest(URI,"");
}
function tabListener(type,Uri,params,reqFrom)
{
    
    //var bEnquiryURI=getPreferenceVal("extensions.commlink.ibbenqurl","");
    
    
    var refFunc=function(event)
    {
        try
        {

       
            //alert(event.target);

            var gbrowser="";

            if(reqFrom=="window")
            {
                gbrowser=window.opener.gBrowser;
               
            }
            else if(reqFrom=="chrome")
            {
                gbrowser=gBrowser;

            }


            var currentDocumentBody = gbrowser.getBrowserForTab(event.target).contentDocument.body;
            

            if($(currentDocumentBody).html()!="")
            {
                
                

                //
                //alert($(currentDocumentBody).html()+1);
                //event target returns object which register the event
                //alert("success");
                event.target.removeEventListener("load",refFunc , true)
                //                var uAccNo=getPreferenceVal("extensions.commlink.ibuseraccno");
                if(type==0)
                {
                    sendGetRequest(Uri+"?acno="+params.accNo);
                }
                else if(type==1)
                {
                    
                    msg=$(currentDocumentBody).html();
                    var message=msg.match(/Name:\s+([\w\s]+)/i);
                    var postData="acno="+params.accNo+"&acname="+message[1]+"&fdate="+params.fDate+"&tdate="+params.tDate;
                    gbrowser.removeTab(event.target);
                    makePostRequest(Uri,postData,"window");
                    //gbrowser.loadURI(Uri, "", postData);
                    //
                    //alert(postData);
                    //                    const REF_URI = Components.Constructor("@mozilla.org/network/standard-url;1", "nsIURI");
                    //                    var REF = new REF_URI;
                    //                    gbrowser.loadURI(Uri,REF,postData,false);
                    window.close();
                }
            //newTabBrowser.removeEventListener("load", null, true);

            }


        }catch(msg)
        {
            alert(msg);
        }
    }
    return refFunc;
}



function ajaxresp(msg) {
    
    var uName=getPreferenceVal("extensions.commlink.attnid","");
    var password="";
    var id=null;
    if(uName!="")
    {
        password=getPassword(hNameAttn,subURL,httprealmAttn,uName);
        var regExp=new RegExp(uName+'[\\w\\d\\s&;<\\/>""=\\-:.]+\\?[a-zA-Z=]+[0-9]+[&a-zA-Z=;]+([0-9]+)[&a-zA-Z]+=login',"i");
        var output=msg.match(regExp);
        if(output!=null)
        {
            id=output[1];
            var postData="username="+uName+"&password="+password+"&action=makeLoginLogout&requestedaction=logout&attendanceid="+id;
            var URI=getPreferenceVal("extensions.commlink.attendanceURL","");
            makePostRequest(URI,postData);
            
        }
        else
        {
            alert("You didn't login Or Invalid User Name");
        }
    }
    else
    {
        alert("Set your account first");
        window.openDialog("chrome://sample/content/pref.xul", "Settings","modal=yes,chrome=yes,centerscreen=yes");
        
    }

}

function ajaxRequest(type, url, serverdata, succfunc,async,pData,errorfunc) {

    
    //alert(serverdata.username);
    if(errorfunc==null)
    {
        errorfunc= function(msg)
        {
            alert(msg);
        }
    }
    $.ajax({
        async:async,
        type: type,
        url: url,
        data: serverdata,
        success: succfunc,
        processData:pData,
        error: errorfunc
    });
    
    
}

var loginInfo={
    
    username:"",
    password:"",
    action:"",
    requestedaction:"",
    inoutid:"",
    inoutpurposeid:"",
    description:""
    
};

function makePostRequest(url,data,requestFrom)
{
    //var dataString="alias=pmtamal&password=010386buet45678&dologin=1&user_name=pmtamal";
    
    var dataString=data;
    //var dataString = "alias=pmtamal&password=010386buet45678&dologin=1&user_name=pmtamal";
    const REF_URI = Components.Constructor("@mozilla.org/network/standard-url;1", "nsIURI");
    var REF = new REF_URI;
    // POST method requests must wrap the encoded text in a MIME  stream
    const Cc = Components.classes;
    const Ci = Components.interfaces;
    var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
    createInstance(Ci.nsIStringInputStream);
    if ("data" in stringStream) // Gecko 1.9 or newer
        stringStream.data = dataString;
    else // 1.8 or older
        stringStream.setData(dataString, dataString.length);

    var postData = Cc["@mozilla.org/network/mime-input-stream;1"].
    createInstance(Ci.nsIMIMEInputStream);
    postData.addHeader("Content-Type", "application/x-www-form-urlencoded");

    postData.addContentLength = true;
    postData.setData(stringStream);
    //var newTab=gBrowser.getBrowserForTab(gBrowser.addTab(url,REF,null,postData));
    var gbrowser="";

    //alert("requestfrom"+requestFrom);
    if(requestFrom=="window")
    {
        gbrowser=window.opener.gBrowser;
    }
    else
    {
        gbrowser=gBrowser;
    }

    gbrowser.selectedTab = gbrowser.addTab(url,REF,null,postData);

    return gbrowser.selectedTab;
    
}
function sendGetRequest(url)
{
   
    const REF_URI = Components.Constructor("@mozilla.org/network/standard-url;1", "nsIURI");
    var REF = new REF_URI;
    openUILink(url,null,false,true);
//gBrowser.selectedTab = gBrowser.addTab(url,REF,null);
}
function makePostRequestOutsideBrowser(url,data)
{
    var dataString=data;
    //var dataString = "alias=pmtamal&password=010386buet45678&dologin=1&user_name=pmtamal";
    const REF_URI = Components.Constructor("@mozilla.org/network/standard-url;1", "nsIURI");
    var REF = new REF_URI;
    // POST method requests must wrap the encoded text in a MIME  stream
    const Cc = Components.classes;
    const Ci = Components.interfaces;
    var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
    createInstance(Ci.nsIStringInputStream);
    if ("data" in stringStream) // Gecko 1.9 or newer
        stringStream.data = dataString;
    else // 1.8 or older
        stringStream.setData(dataString, dataString.length);

    var postData = Cc["@mozilla.org/network/mime-input-stream;1"].
    createInstance(Ci.nsIMIMEInputStream);
    postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
    postData.addContentLength = true;
    postData.setData(stringStream);
    var gbrowser=window.opener.gBrowser;
    gbrowser.selectedTab =gbrowser.addTab(url,REF,null,postData);
}

function OpenExecutable(path)
{
    alert(path);
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    var file = Components.classes["@mozilla.org/file/local;1"]
    .createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath(path);

    // create an nsIProcess
    var process = Components.classes["@mozilla.org/process/util;1"]
    .createInstance(Components.interfaces.nsIProcess);
    process.init(file);

    // Run the process.
    // If first param is true, calling thread will be blocked until
    // called process terminates.
    // Second and third params are used to pass command-line arguments
    // to the process.
    var args = ["argument1", "argument2"];
    process.run(true, null, null);

}
function contextClick()
{
    alert(1);
    alert(getBrowserSelection(25));
    //$("<div><p>Hello</p></div>").appendTo("body");
    //$(document.body).css( "background", "black" );
    //alert(document.getElementsByTagName("body").style.backgroundcolor);
    //    var bod=document.getElementsByTagName("body");
    //    bod.setAttribute("background", "#000");

    var currentDocument = gBrowser.contentDocument;
    //$(currentDocument.body).css( "background", "black" )
    alert($(currentDocument.body).width());
    //alert(currentDocument.width);
    $(currentDocument.body).append('<div style="position:absolute;top:0px">Hello</div>');
    //$("<div><p>Hello</p></div>").appendTo(currentDocument.body+"")
    //currentDocument.body.style.backgroundColor = "magenta";
    //currentDocument.body.setAttribute("background", "#000");
    //BrowserReload();


    //alert(bod.style.backgroundcolor);
    //bod.style.backgroundcolor="#000";

    //alert(document.body.);
    alert(2);


}
function unClosedLogin()
{
    
    var time_hour=$('#time_Hour').val();
    var time_minute=$('#time_Minute').val();
    var time_second=$('#time_Second').val();
    var remarks=$('#remarks').val();

    var uName=getPreferenceVal("extensions.commlink.attnid","");
    var password="";
    
    var employeeId=getPreferenceVal("extensions.commlink.employeeid","")
    var omsUnclosedLoginURI=getPreferenceVal("extensions.commlink.omsUnclosedloginURL","");
    var omsLoginURI=getPreferenceVal("extensions.commlink.omsloginURL","");
    var attnURI=getPreferenceVal("extensions.commlink.attendanceURL","");
    
    if(uName!="")
    {
        password=getPassword(hNameAttn,subURL,httprealmAttn,uName);
        //window.opener.gBrowser.addTab("http://www.commlinkinfotech.com"); //var URI='https://172.16.0.3/oms/ocp/showDocument.php?documentid=1';
        ajaxRequest("post",omsLoginURI ,{
            username:uName,
            password:password,
            action:"login"
        }, function serverRsp(msg)

        {
        
                ajaxRequest("get", omsUnclosedLoginURI,"",function uLoginRsp(msg){
                    var output=msg.match(/days[\w\d\s;<\/>""=\-:.]+&[\w\s;<\/>""=\-:.,?]+[\D]+([0-9]+)/i);
                    var id=output[1];
                    
                    var URI=omsUnclosedLoginURI+"&employeeid="+employeeId;
                    var postData="id="+id+"&action=makeLogout&time_Hour="+time_hour+"&time_Minute="+time_minute+"&time_Second="+time_second+"&remarks="+remarks;
                    ajaxRequest("post",URI,postData,function uLogoutRsp(msg){

                        var postData="username="+uName+"&password="+password+"&action=makeLoginLogout&requestedaction=login";
                        var URI=attnURI;
                        makePostRequestOutsideBrowser(URI,postData);

                    },false);

                },false,true );
       
    

            },false,true);
    }
    else
    {
        alert("Set your account first");
    }


}

function showPassword()
{
    var uNameMail=getPreferenceVal("extensions.commlink.mailid","");
    var password=getPassword(hNameMail,subURL,httprealmMail,uNameMail);
    if(password!=null)
    {
        $("#mailpass").val(password);
    }
    var uNameAttn=getPreferenceVal("extensions.commlink.attnid","");
    password=getPassword(hNameAttn,subURL,httprealmAttn,uNameAttn);
    if(password!=null)
    {
        $("#attnpass").val(password);
    }
    var uCodeIb=getPreferenceVal("extensions.commlink.ibusercode","");
    password=getPassword(hNameIb,subURL,httprealmIb,uCodeIb);
    if(password!=null)
    {
        $("#ibpass").val(password);
    }
}

function getPassword(hostname,formSubmitURL,httpRealm,username)
{
    
    try
    {

        if(username!="")
        {
            var loginInfo=selectLoginInfo(hostname,formSubmitURL,httpRealm,username);
            if(loginInfo!=null)
            {

                //return (loginInfo.username==username)?loginInfo.password:null;
                return (loginInfo.password==" ")?"":loginInfo.password;
            //$("#"+tboxID).val(loginInfo.password);

            }
    

        }
    }catch(msg)
    {
        alert(msg);
    }
    return null;



//alert(attURL);

}
function savePassword()
{
    
    try
    {
        var mailpass=($("#mailpass").val()=="")?" ":$("#mailpass").val();
        var attnpass=($("#attnpass").val()=="")?" ":$("#attnpass").val();
        var mailId=$("#mailid").val();
        var attId=$("#attnid").val();
        var ibUserCode=$("#ibusercode").val();
        var ibUserpass=($("#ibpass").val()=="")?" ":$("#ibpass").val();


    
    
        if(mailpass!="")
        {
            insertPassword(hNameMail,subURL,httprealmMail,mailId,mailpass);
        }
        if(attnpass!="")
        {
            insertPassword(hNameAttn,subURL,httprealmAttn,attId,attnpass);
        }
        if(ibUserpass!="")
        {
            insertPassword(hNameIb ,subURL,httprealmIb,ibUserCode,ibUserpass);
        }
    }catch(msg)
    {
        alert(msg);
    }
    
    
    
    return true;

}

function getLoginInfo(hostname,formSubmitURL,httpRealm,username,password,usernameField,passwordField)
{
    var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
        Components.interfaces.nsILoginInfo,
        "init");
    return new nsLoginInfo(hostname,formSubmitURL,httpRealm,username,password,usernameField,passwordField);
}
function getLoginManager()
{
    var myLoginManager = Components.classes["@mozilla.org/login-manager;1"]
    .getService(Components.interfaces.nsILoginManager);
    return myLoginManager;
}

function insertPassword(hostName,formSubmitURL,httpRealm,userName,passWord)
{

    
    try
    {
        var hName=hostName;
        var subURL=formSubmitURL;
        var httprealm=httpRealm;
        var uName=userName;
        var password=passWord;
    
        var newLoginInfo = new getLoginInfo(hName,subURL,httprealm,uName,password,"", "");
        var myLoginManager=getLoginManager();

        var logins = myLoginManager.findLogins({}, hName, subURL, httprealm);
        var modify=false;


        for(i=0;i<logins.length;i++)
        {
            if(logins[i].username==uName)
            {
                modify=true;
                break;
            }
        }
    
        if(modify==true)
        {
        
        
            myLoginManager.modifyLogin(logins[i], newLoginInfo);
                
        }
        else
        {
        
            myLoginManager.addLogin(newLoginInfo);
            
        }
    }catch(msg)
    {
        alert(msg);
    }

}
function selectLoginInfo(hostName,formSubmitURL,httpRealm,userName)
{

    var hName=hostName;
    var subURL=formSubmitURL;
    var httprealm=httpRealm;
    var uName=userName;

    var myLoginManager =getLoginManager();
    var logins = myLoginManager.findLogins({}, hName, subURL, httprealm);
    if(logins.length>0)
    {
        
        for(i=0;i<logins.length;i++)
        {
            if(logins[i].username==uName)
            {
                return logins[i];
                
            }
        }

        
    }
    return null;


}
function showSettings(){
    window.openDialog("chrome://sample/content/pref.xul", "Settings","modal=yes,chrome=yes,centerscreen=yes");
}

function openXulDialogue(name,title,attribute)
{
    window.openDialog(name, title,attribute);
}

function onStatementXulLoad()
{
    var tdate=new Date();
    var fdate=new Date();
    fdate.setDate(fdate.getDate()-30);
    document.getElementById("fdate").value=fdate.getFullYear()+"-"+(fdate.getMonth()+1)+"-"+fdate.getDate();
//document.getElementById("tdate").value=tdate.getFullYear()+"-"+(tdate.getMonth()+1)+"-"+tdate.getDate();
    
    
    
}

function anyWebSiteLogin(sitename,uname,password)
{
    //alert("Start login");
    var unameIndex=0;
    var url="",uindex=0,liveyes=0;
    switch(sitename)
    {
        case "facebook":
            url=getPreferenceVal("extensions.commlink.fburi","");
            uindex=0;
            break;
        case "gmail":
            url=getPreferenceVal("extensions.commlink.gmailuri","");
            uindex=1;
            break;
        case "csebuet":
            url=getPreferenceVal("extensions.commlink.csebueturi","");
            uindex=2;
            break;
        case "yahoo":
            url=getPreferenceVal("extensions.commlink.yahoouri","");
            uindex=3;
            break;
        case "cmail":
            url=getPreferenceVal("extensions.commlink.cmailuri","");
            uindex=5;
            break;
        case "winlive":
            url=getPreferenceVal("extensions.commlink.liveuri","");
            uindex=4;
            liveyes=1;
            break;
        default:
            break;


    }
    openHomeAfterLogin(uindex,url,uname,password,liveyes);
    
}


function openHomeAfterLogin(index,url,uname,password,liveyes)
{
      
    $("#loading").attr("hidden","false");
    logincount++;
    ajaxRequest("get",url,"",function gmail(data){

        try
        {


            //alert(data);
            var DOMPars = HTMLParser(data);
            var postData="";
            var action=DOMPars.getElementsByTagName("form")[0].action;
            //alert(action);
            //alert(DOMPars.getElementsByTagName("form")[0].action);
            //var csebuetaction="https://www.google.com/a/csebuet.org/LoginAction2?service=mail"

            //facebook=3,live 2

            //alert(loginName[""]);
            var doc= DOMPars.getElementsByTagName('input');
            for(i=0;;i++)
            {
                
                if(index==0)
                {
                    if(doc[i].name==loginName.facebook)break;
                }
                else if(index==1 ||index==5)
                {
                    if(doc[i].name==loginName.gmail)break;
                }
                else if(index==2)
                {
                    if(doc[i].name==loginName.csebuet)break;
                }
                else if(index==3)
                {
                    if(doc[i].name==loginName.yahoo)break;
                }
                else if(index==3)
                {
                    if(doc[i].name==loginName.yahoo)break;
                }

                //if(doc[i].name==loginName.facebook)break;
                postData=postData+doc[i].name+"="+escape(doc[i].value)+"&";
            }
            postData+=doc[i++].name+"="+uname+"&"+doc[i++].name+"="+password+"&";
            //alert(postData);
            for(;i<doc.length;i++)
            {
                postData=postData+doc[i].name+"="+escape(doc[i].value)+"&";
            }
            //alert(postData);


            
            if(liveyes==1)
            {
                ajaxRequest("post",action,postData,function loginrsp(data){
                    makePostRequest("http://mail.live.com","");
                    hideLoadingImage();
                },true,true);
            }
            else
            {
                
                
                makePostRequest(action,postData);
            }
            
        //makePostRequest(csebuetaction,postData);
        //alert(DOMPars.getElementsByTagName('input')[0].name)

        }catch(msg)
        {
            //alert(msg);
            makePostRequest(url,"");
            
        }
        if(liveyes!=1)
        {
            hideLoadingImage();
        }
        

    },true,true,function error(msg){
        alert("Network Error.Please try later or contact network administrator");
        $("#loading").attr("hidden","true");
    });
}
function hideLoadingImage()
{
    logincount--;
    //alert("as"+logincount);
    if(logincount==0)
    {
        $("#loading").attr("hidden","true");
    }
}
function writecookie(name,value)
{
    createCookie(name,value,0);
}
function readcookie(name)
{
    alert(readCookie(name));
}

function onEmailXulLoad(){

  
    var email=window.arguments[0].inn.email;
    var historyName=window.arguments[0].inn.formhistory;
    //alert(historyName);
    $("#email").attr("autocompletesearchparam",historyName);
    $("#emailname").attr("label",email);
    
}

function populatePassword(mailHost)
{
    
   
    var hNameMail="chrome://autologin-"+mailHost;
    var httprealmMail=mailHost + " Login";
    var emailId=$("#email").val();
    var password=getPassword(hNameMail,subURL,httprealmMail,emailId);
    if(password!=null)
    {

        password=jQuery.trim(password)
        $("#passwd").val(password);

    }

}
function dummyfunc()
{
    var params={
        inn:{
            email:"gmail"
        },
        out:null
    };
    //openXulDialogue("chrome://sample/content/emailInfo.xul", "Account Statement","modal=yes,chrome=yes,centerscreen=yes",params).focus();
    window.openDialog("chrome://sample/content/emailInfo.xul", "Account Statement","modal=yes,chrome=yes,centerscreen=yes",params).focus();
//alert(params.out.eid+params.out.epasswd+params.out.rm);
}

function addHistory(historyName,email)
{
     
    var fhService = Components.classes["@mozilla.org/satchel/form-history;1"].
    getService(Components.interfaces.nsIFormHistory2);
    fhService.addEntry(historyName,email);
}
function openMailLoginXul(mailHost)
{


    var historyName=mailHost+"autocomplete";
    var params={
        inn:{
            email:mailHost,
            formhistory:historyName
        },
        out:null
    };
    window.openDialog("chrome://sample/content/emailInfo.xul", "Account Statement","modal=yes,chrome=yes,centerscreen=yes",params).focus();

    var hNameMail="chrome://autologin-"+mailHost;
    var httprealmMail=mailHost + " Login";
    var emailId=params.out.eid;
    var password=" ";
    //alert(params.out.eid+params.out.epasswd+params.out.rm);
    if(params.out.rm=="true")
    {
        password=params.out.epasswd;
        insertPassword(hNameMail,subURL,httprealmMail,emailId,password);

    }
    //alert(params.out.eid+params.out.epasswd+params.out.rm);
    addHistory(historyName,emailId);
    anyWebSiteLogin(mailHost,emailId,params.out.epasswd)
//alert(params.out.eid+params.out.epasswd+params.out.rm);

}

function emailOnOk()
{
    var emailId=$("#email").val();
    var passwd=$("#passwd").val();
    var rm=$("#chkboxrm").attr("checked");
    window.arguments[0].out={
        eid:emailId,
        epasswd:passwd,
        rm:rm
    } ;
    
}
